#!/usr/bin/perl -w
use strict;
use DBI;
use Statistics::Descriptive;

# Jason Weirather
# this will take a human bed file and convert it into
# a more generic format for other species.  it stores
# info about it in the database.  You will be able to
# it will allow you to track the original source of the
# feature if it is used.

# this will load a bed file into the database so it will be usable by other programs.
#### we need to bring in quite a bit of information to properly label any thing we load
#warning!  it uses temp files.  multiple instances will be crippled for now. 
#this depends on liftOver from UCSC.  It needs to be in the same directory as this
#and your peak files.
my $filename = shift(@ARGV);
open(FH,"/tmp/translate_bed.txt");
chomp(my $species = <FH>);
chomp(my $original_source = <FH>);
chomp(my $feature_name = <FH>); 
chomp(my $cell_type = <FH>);
chomp(my $note = <FH>);      
chomp(my $replicate_number = <FH>);
chomp(my $conversion = <FH>);
chomp(my $original_species = <FH>);

#### conversion specific information

#### do the conversion ### this is depreciated since local liftover does not work.
#foreach my $line (@lines) {
chomp(my @lines = <FH>);
my %oldentries;
foreach my $line (@lines) {
  my @fields = split(/\t/,$line);
  $oldentries{$fields[0]} = "$fields[1]\t$fields[2]\t$fields[3]\t$fields[4]";
}
close FH;
open(OF,"/tmp/after_liftover.bed");
chomp(my @converted_lines = <OF>);
close OF;
#foreach my $line (@converted_lines) {
#  print "$line";
#}

my @lines_to_add;
#chomp(my @lines = <STDIN>);
my $total_width = 0;
my $widthstat = Statistics::Descriptive::Full->new();
my $heightstat = Statistics::Descriptive::Full->new();
foreach my $line (@converted_lines) {
  my @fields = split(/\t/,$line);
  my $midpoint = int (($fields[1] + $fields[2])/2);
  my $oldline = $oldentries{$fields[3]};
  my @oldfields = split(/\t/,$oldline);
  my $ln = "$fields[0]\t$fields[1]\t$fields[2]\t$oldfields[3]\t$midpoint\t$oldfields[0]\t$oldfields[1]\t$oldfields[2]";
  push @lines_to_add, $ln;
  $widthstat->add_data($fields[2]-$fields[1]);
  $heightstat->add_data($oldfields[3]);
}
print $widthstat->max() . " " . $heightstat->max() . "\n";
print $widthstat->mean() . " " . $heightstat->mean() . "\n";
print $widthstat->standard_deviation() . " " . $heightstat->standard_deviation() . "\n";

#open(OF,">/tmp/temppeaks0.bed");
#foreach my $line (@lines_to_add) {
#  print OF $line . "\n";
#}
#die;

my $zdatabase = "zebraphish";
my $platform = "mysql";
my $user = 'x';
my $zdbh = DBI->connect("dbi:$platform:$zdatabase",$user,'');
my $zquery = "SELECT db_id FROM feature_overlay_info WHERE species = '$species' AND original_source = '$original_source' AND feature_name = '$feature_name' AND cell_type = '$cell_type' AND replicate_number = $replicate_number ORDER BY db_id DESC LIMIT 1";
print "$zquery\n";
my $zst = $zdbh->prepare($zquery) or die "preparing query failed: $DBI::errstr";
$zst->execute() or die "The execution of query field: $DBI::errstr";
while(my $row = $zst->fetchrow_hashref()) {
  die "already did this one.\n";
}

$zquery = "INSERT INTO feature_overlay_info (species,original_source,feature_name,cell_type,replicate_number,note,average_peak_height,average_peak_width,stddev_peak_height,stddev_peak_width,conversion,original_species) VALUES ('$species','$original_source','$feature_name','$cell_type',$replicate_number,'$note'," . $heightstat->mean() . "," . $widthstat->mean() . "," . $heightstat->standard_deviation() . "," . $widthstat->standard_deviation() . ",'$conversion','$original_species')";
print "$zquery\n";
$zst = $zdbh->prepare($zquery) or die "preparing query failed: $DBI::errstr";
$zst->execute() or die "The execution of query field: $DBI::errstr";
###########

#################
###This assumes that we are using the most recent addition.
###this may not always be the case so be careful.
$zquery = "SELECT db_id FROM feature_overlay_info ORDER BY db_id DESC LIMIT 1";
print "$zquery\n";
$zst = $zdbh->prepare($zquery) or die "preparing query failed: $DBI::errstr";
$zst->execute() or die "The execution of query field: $DBI::errstr";
my $db_id;
while(my $row = $zst->fetchrow_hashref()) {
  $db_id = $row->{'db_id'};
}
print "$db_id\n";
foreach my $line (@lines_to_add) {
  my ($chromosome,$start,$finish,$score,$midpoint,$origchrom,$origstart,$origfinish) = split(/\t/,$line);
  $zquery = "INSERT INTO feature_overlay (feature_overlay_info_id,chromosome,start,finish,score,midpoint,original_chromosome,original_start,original_finish) VALUES ('$db_id','$chromosome','$start','$finish','$score','$midpoint','$origchrom','$origstart','$origfinish')";
  print "$zquery\n";
  $zst = $zdbh->prepare($zquery) or die "preparing query failed: $DBI::errstr";
  $zst->execute() or die "The execution of query field: $DBI::errstr";
}
